<?php

/**
 * This is the model class for table "product".
 *
 * The followings are the available columns in table 'product':
 * @property integer $identification
 * @property integer $category
 * @property string $subject
 * @property string $image
 * @property string $price
 * @property integer $vat
 * @property string $description
 * @property string $content
 * @property string $url_mapping
 * @property string $note
 * @property string $insert
 * @property string $update
 * @property string $delete
 *
 * The followings are the available model relations:
 * @property OrderDetail[] $orderDetails
 * @property Category $category0
 * @property ProductImage[] $productImages
 */
class Product extends CActiveRecord
{
    public $key;
    public $category_name;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Product the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'product';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('category, subject, content', 'required'),
            array('category, vat', 'numerical', 'integerOnly'=>true),
            array('subject', 'length', 'max'=>140),
            array('image, url_mapping', 'length', 'max'=>255),
            array('price', 'length', 'max'=>10),
            array('description, note, insert, update, delete', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('identification, category, subject, image, price, vat, description, content, url_mapping, note, insert, update, delete', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'orderDetails' => array(self::HAS_MANY, 'OrderDetail', 'product'),
            'category0' => array(self::BELONGS_TO, 'Category', 'category'),
            'productImages' => array(self::HAS_MANY, 'ProductImage', 'product'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'identification' => 'Key',
            'category' => 'Category',
            'subject' => 'Subject',
            'image' => 'Image',
            'price' => 'Price',
            'vat' => 'Vat',
            'description' => 'Description',
            'content' => 'Content',
            'url_mapping' => 'Url Mapping',
            'note' => 'Note',
            'insert' => 'Insert',
            'update' => 'Update',
            'delete' => 'Delete',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('identification',$this->identification);
        $criteria->compare('category',$this->category);
        $criteria->compare('subject',$this->subject,true);
        $criteria->compare('image',$this->image,true);
        $criteria->compare('price',$this->price,true);
        $criteria->compare('vat',$this->vat);
        $criteria->compare('description',$this->description,true);
        $criteria->compare('content',$this->content,true);
        $criteria->compare('url_mapping',$this->url_mapping,true);
        $criteria->compare('note',$this->note,true);
        $criteria->compare('insert',$this->insert,true);
        $criteria->compare('update',$this->update,true);
        $criteria->compare('delete',$this->delete,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }


    /** getDataByID =============================
     * @author   TuanNguyen
     * @desc     get product entity from database
     * @param    integer $i_id: key of product record
     * @return   Product Entity
     *           ErrorEntity: if there are an error in database
     * ============================================== */
    public static function getDataByID($i_id)
    {
        //Set SQL command
        $command = Yii::app()->db->createCommand("CALL product_02_getid(:p_id)");

        //Set parameter for SQL command
        $command->bindValue("p_id", $i_id,PDO::PARAM_INT);
        
        try
        {
            $row = $command->queryRow();

            if($row !=null)
            {
                $m_model = new Product();
                $m_model->unsetAttributes();

                $m_model->identification    = $row["identification"];
                $m_model->key               = $row["identification"];
                $m_model->category          = $row["category"];
                $m_model->category_name     = $row["category_name"];
                $m_model->subject           = $row["subject"];
                $m_model->image             = $row["image"];
                $m_model->price             = $row["price"];
                $m_model->vat               = $row["vat"];
                $m_model->description       = $row["description"];
                $m_model->content           = $row["content"];
                $m_model->url_mapping       = $row["url_mapping"];
                $m_model->note              = $row["note"];
                $m_model->insert            = $row["insert"];
                $m_model->update            = $row["update"];
                $m_model->delete            = $row["delete"];

                return $m_model;
            }

            return null;
        }
        catch (CDbException $ex)
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_2";
            $o_error->param     = array("SQLException" => $ex->getMessage());
            return $o_error;
        }
    }//End getDataByID


    /** addDataToDb =============================
     * @author   TuanNguyen
     * @desc     save product, product image entity to database
     * @param    string $p_insertStaement: string for values in insert statement
     * @return   boolean
     *           ErrorEntity: if there are an error in database
     * ============================================== */
    public static function addDataToDb(Product $o_product, $s_proImgStatement = null)
    {
        $command = Yii::app()->db->createCommand("CALL product_03_insert
            (
                :p_category,
                :p_subject,
                :p_image,
                :p_price,
                :p_description,
                :p_content,
                :p_url,
                :p_vat,
                :p_pistatement
            )");

        $command->bindValue("p_category", $o_product->category,PDO::PARAM_INT);
        $command->bindValue("p_subject", CHtml::encode($o_product->subject));
        $command->bindValue("p_image",$o_product->image);
        $command->bindValue("p_price",$o_product->price);
        $command->bindValue("p_description",CHtml::encode($o_product->description));
        $command->bindValue("p_content",CHtml::encode($o_product->content));
        $command->bindValue("p_url",$o_product->url_mapping);
        $command->bindValue("p_vat",$o_product->vat,PDO::PARAM_INT);
        $command->bindValue("p_pistatement",$s_proImgStatement);

        try
        {
            $i_result = $command->execute();

            if($i_result >=1)
                return true;

            return false;
        }
        catch (CDbException $ex)
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_2";
            $o_error->param     = array("SQLException" => $ex->getMessage());
            return $o_error;
        }
    }//End addDataToDb


    /** updateDataToDb =============================
     * @author   TuanNguyen
     * @desc     update product, add product image entity to database
     * @param    string $p_insertStaement: string for values in insert statement
     * @return   boolean
     *           ErrorEntity: if there are an error in database
     * ============================================== */
    public static function updateDataToDb(Product $o_product, $s_proImgStatement = null)
    {
        $command = Yii::app()->db->createCommand("CALL product_04_update
            (
                :p_key,
                :p_category,
                :p_subject,
                :p_image,
                :p_price,
                :p_description,
                :p_content,
                :p_url,
                :p_vat,
                :p_pistatement
            )");
    
        $command->bindValue("p_key",$o_product->key,PDO::PARAM_INT);
        $command->bindValue("p_category", $o_product->category,PDO::PARAM_INT);
        $command->bindValue("p_subject", CHtml::encode($o_product->subject));
        $command->bindValue("p_image",$o_product->image);
        $command->bindValue("p_price",$o_product->price);
        $command->bindValue("p_description",CHtml::encode($o_product->description));
        $command->bindValue("p_content",CHtml::encode($o_product->content));
        $command->bindValue("p_url",$o_product->url_mapping);
        $command->bindValue("p_vat",$o_product->vat,PDO::PARAM_INT);
        $command->bindValue("p_pistatement",$s_proImgStatement);
    
        try
        {
            $m_model = null;
            $row     = $command->queryRow();

            if($row !=null)
            {
                $m_model = new Product();
                $m_model->unsetAttributes();

                $d_insert = new DateTime($row["insert"]);
                $dou_price = number_format($row["price"],0);

                $m_model->key = $row["identification"];
                $m_model->subject = $row["subject"];
                $m_model->category_name = $row["category_name"];
                $m_model->price = $dou_price;
                $m_model->vat = $row["vat"];
                $m_model->insert = $d_insert->format("Y-m-d");
            }//End if

            return $m_model;
        }
        catch (CDbException $ex)
        {
            $o_error            = new ErrorEntity();
            $o_error->errCode   = "ERR_2";
            $o_error->param     = array("SQLException" => $ex->getMessage());
            return $o_error;
        }
    }//End updateDataToDb
}